package org.tio.sitexxx.web.server.controller.gl;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.*;
import org.tio.sitexxx.service.service.gl.ConsultantManageService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.crypto.Md5;
import org.tio.utils.resp.Resp;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 顾问管理
 */
@RequestPath("/gl/manage/consultant")
public class ConsultantManage {
    private static Logger log = LoggerFactory.getLogger(AdminController.class);

    /**
     * 返回顾问列表
     */
    @RequestPath("/list")
    public Resp consultantList(Integer pageNumber,Integer pageSize){
        if(pageNumber==null||pageSize==null)return Resp.fail("参数错误");
        Page<Record> consultants = ConsultantManageService.me.ConsultantList(pageNumber,pageSize);
        if(consultants==null||consultants.getList().size()==0)
            return Resp.fail();
        return Resp.ok(consultants);
    }

    /**
     * 顾问详细信息
     */
    @RequestPath("/person-information")
    public Resp consultantInformation(Integer id){
        if(id==null)return  Resp.fail();
        Map<String,Object>  information = new HashMap<>();
        Consultant consultant = Consultant.dao.findById(id);
        Interest interest = Interest.dao.findById(consultant.getInterestId());
        information.put("person",consultant);
        information.put("interest",interest);
        return Resp.ok(information);
    }

    /**
     * 方案列表
     * id  顾问id
     */
    @RequestPath("/order/byconsultant")
    public Resp orderListByConsultant(Integer id,Integer pageNumber,Integer pageSize){
        if(id==null)return  Resp.fail();
        Page<Record> payments =ConsultantManageService.me.getDesignByConsultantid(id,pageNumber,pageSize);
        if(payments==null||payments.getList().size()==0)
            return Resp.fail();
        return Resp.ok(payments);
    }

    /**
     * 根据顾问id查找完成的kf订单
     * @param id
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestPath("/payment/byconsultant")
    public Resp kfPaymentListByConsultant(Integer id,Integer pageNumber,Integer pageSize){
        if(id==null)return  Resp.fail();
        Page<Payment> paymentPage = ConsultantManageService.me.kfPaymentListByConsultant(id,pageNumber,pageSize);
        if(paymentPage==null||paymentPage.getList().size()==0)
            return Resp.fail();
        return Resp.ok(paymentPage);
    }

    /**
     * 修改顾问密码
     */
    @RequestPath("/update/password")
    public Resp updatePassword(Integer id,String password){
        boolean result = Consultant.dao.findById(id).set("password", Md5.getMD5(password)).update();
        if(result)
            return Resp.ok();
        return Resp.fail();
    }

    /**
     * 修改顾问信息
     */
    @RequestPath("/update/information")
    public Resp updateInformation(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            Integer id=Integer.valueOf(map.get("id").toString());
            Integer level=Integer.valueOf(map.get("level").toString());
            Integer fee=Integer.valueOf(map.get("fee").toString());
            Integer real_fee=Integer.valueOf(map.get("real_fee").toString());
            String recommeded_reason=map.get("recommeded_reason").toString();
            Consultant consultant = Consultant.dao.findById(id);
            consultant.setConsultationFees(fee);
            consultant.setExperienceFees(real_fee);
            consultant.setRecommendedReason(recommeded_reason);
            Db.tx(()->{
                boolean result2=true;
                if(consultant.getInterestId()!=null){
                    Interest interest = Interest.dao.findById(consultant.getInterestId());
                    interest.setGrade(level+"");
                    result2=interest.update();
                }else{
                    Date date=new Date();
                    Record interest=new Record().set("id",consultant.getId()).set("commission_rate",0.5f).set("grade",level+"").set("createdAt",date).set("updatedAt",date);
                    result2=Db.use(Const.Db.TIO_SITE_MAIN).save("interest","id",interest);
                    int key=Integer.valueOf(interest.get("id").toString());
                    System.out.println("k:"+key);
                    consultant.setInterestId(key);
                }
                boolean result1 = consultant.update();
                if(result1&&result2){
                    return true;
                }
                return false;
            });
        }catch (NullPointerException e){
            log.error(e.toString(),e);
            return Resp.fail("参数错误");
        }catch (NumberFormatException e){
            log.error(e.toString(),e);
            return Resp.fail("部分参数不能为空");
        } catch (Exception se){
            log.error(se.toString(),se);
            return Resp.fail();
        }
        return Resp.ok();
    }

    /**
     * 方案，问题详情
     * @param id 方案id
     * @return
     */
    @RequestPath("/query/design")
    public Resp queryDesignByDesignId(Integer id){
        if(null==id)return Resp.fail();
        Resp resp = Resp.ok();
        Map<String,Object> map = new HashMap<>();
        Db.tx(()->{
            Design design = Design.dao.findById(id);
            Question question = Question.dao.findById(design.getFDesignId());
            map.put("design",design);
            map.put("question",question);
            return true;
        });
        if(map==null)
            return Resp.fail();
        resp.setData(map);
        return resp;
    }




}
